module Base
  module Helper
    attr_accessor :current_user

    protected

    def authenticate!
      # error!({msg:"未登录"}, 200)
      # raise "未登录"
      @current_user = AdminUser.find_by(id: decode[:user_id])
      error("未登录") if @current_user.blank?
    end

    def error(message = "请求失败", code = 40000)
      raise APIError.new(message: message, code: code)
    end

    def render_json(data = {}, success = true)
      {
        code: 20000,
        success:success,
        data: data
      }
    end
    
    private

    def decode
      HashWithIndifferentAccess.new(JWT.decode(request.headers['Authorization'], Rails.application.secrets.secret_key_base)[0])
    rescue
      raise "未登录"
    end
  end
end
  